package com.ziq.zcamp.login

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import com.blankj.utilcode.util.BarUtils
import com.facebook.imagepipeline.request.ImageRequest
import com.ziq.base.base.BaseActivity
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.base.extension.launchWithTry
import com.ziq.base.utils.KeyboardUtil
import com.ziq.base.utils.SystemBarUtil
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.user.PhoneCodeParam
import com.ziq.zcamp.api.request.user.PhoneLoginParam
import com.ziq.zcamp.api.service.UserAccountService
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.databinding.ActivityLoginBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.PrivacyManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.MD5UtilsCompat
import com.ziq.zcamp.util.digest.Hex
import com.ziq.zcamp.util.encrypt.RSAUtils
import dagger.hilt.android.AndroidEntryPoint
import java.io.InputStream
import java.nio.charset.Charset
import java.security.PublicKey
import javax.inject.Inject


@AndroidEntryPoint
class LoginActivity : BaseActivity() {

    @Inject
    lateinit var mUserAccountService: UserAccountService

    companion object {
        fun open(context: Context){
            val intent = Intent(context, LoginActivity::class.java)
            GlobalContextManager.startActivity(context, intent)
        }

        fun checkLogin(action: ActionAfterLogin){
            if(UserManager.instance.isLogin.value == true){
                action.action()
            } else {
                open(GlobalContextManager.appContext!!)
            }
        }
    }


    private val binding : ActivityLoginBinding by binding()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SystemBarUtil.immerseStatusBar(this.window, statusBarIsLight = true)
        binding.root
        ImageUtil.updateImageFromNetwork(binding.ivLogo, "res://drawable/" + R.drawable.ic_logo, ImageRequest.CacheChoice.DEFAULT)
        (binding.back.layoutParams as ConstraintLayout.LayoutParams?)?.let {
            it.topMargin = BarUtils.getStatusBarHeight()
        }
        binding.back.click {
            finish()
        }


        binding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                binding.btnPhoneLogin.isEnabled = !TextUtils.isEmpty(
                    binding.etPhoneSmsCode.text.toString().trim()
                ) && 11 == binding.etPhone.text.toString().trim().length
                binding.btnSmsCode.isEnabled = !binding.etPhone.text.isNullOrEmpty()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        binding.etPhoneSmsCode.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                binding.btnPhoneLogin.isEnabled = !TextUtils.isEmpty(
                    binding.etPhoneSmsCode.text.toString().trim()
                ) && 11 == binding.etPhone.text.toString().trim().length
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        binding.btnSmsCode.setTime(60)
        binding.btnSmsCode.click {
            if(binding.etPhone.text.toString().isEmpty()){
                Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show()
                return@click
            }
            binding.btnSmsCode.startTimer()
            binding.btnSmsCode.isEnabled = false

            launchWithTry(whenTry = {
                val phoneString = binding.etPhone.text.toString()
                val respond = mUserAccountService.phoneCode(PhoneCodeParam().apply {
                    phone = phoneString
                }).request()
            }, whenCatch = {
                Toast.makeText(this, "$it", Toast.LENGTH_SHORT).show()
            })
            binding.etPhoneSmsCode.requestFocus()
        }


        binding.btnPhoneLogin.click {
            KeyboardUtil.hideSoftInputForce(this, binding.root.windowToken)
            binding.btnPhoneLogin.isEnabled = false
            if(!PrivacyManager.isAgreedPrivacy()){
                PrivacyManager.storeAgreedPrivacy()
            }

            launchWithTry(whenTry = {
                val phoneString = binding.etPhone.text.toString()
                val phoneSmsString = binding.etPhoneSmsCode.text.toString()
                val req = PhoneLoginParam().apply {
                    phone = phoneString
                    sms_code = phoneSmsString
                }
                val respond = mUserAccountService.phoneLogin(req).request()
                UserManager.instance.updatePhoneLogin(respond)
                requestUserInfo(respond.data?.uid)
            }, whenCatch = {
                binding.btnPhoneLogin.isEnabled = true
                Toast.makeText(this, "$it", Toast.LENGTH_SHORT).show()
            })
        }
    }


    private fun requestUserInfo(uid : Int?){
        if(uid != null){
            UserManager.instance.requestUserInfo(uid,
                onSuccess = {
                    UserManager.instance.updateUserInfo(it.data)
                    loginSuccess()
                }, onFail = {
                    binding.btnPhoneLogin.isEnabled = true
                    Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
                }
            )
        } else {
            binding.btnPhoneLogin.isEnabled = true
            Toast.makeText(this, "uid 为空", Toast.LENGTH_SHORT).show()
        }
    }

    private fun loginSuccess(){
        Toast.makeText(this, "登录成功",Toast.LENGTH_SHORT).show()
        setResult(Activity.RESULT_OK)
        finish()
    }

    // 获取手机号
    fun getPhone(originPhone : String): String {
        var phone: String = originPhone.trim()
        phone = "86$phone"
        val inPublic: InputStream
        var rsaPhone = ""
        try {
            inPublic = GlobalContextManager.appContext!!.getResources().getAssets().open("rsa_public_key.pem")
            val publicKey: PublicKey = RSAUtils.getPublicKey(inPublic)
            val encryptByte: ByteArray = RSAUtils.encrypt(
                phone.toByteArray(Charset.forName("UTF-8")),
                publicKey
            )
            rsaPhone = Hex.encodeHexString(encryptByte)
        } catch (ignore: Exception) {
        }
        return rsaPhone
    }

    // 获取Secret
    fun getSecret(phone : String): String? {
        val codeSecret = "86" + phone.trim()
        return MD5UtilsCompat.encode(codeSecret.toByteArray(Charset.forName("UTF-8")))
    }


}